package com.aaa.sso.service;

import com.aaa.entity.Permission;
import com.aaa.entity.User;
import com.aaa.sso.feign.PermissionFeign;
import com.aaa.sso.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: aaa-education-parent
 * @description:
 * @author: 闫克起2
 * @create: 2024-03-06 10:54
 **/
@Service
public class MyUserDetailService implements UserDetailsService {
    //单点登录不负责连接数据---关于数据的操作---都在相应的微服务中
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private PermissionFeign permissionFeign;
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        //根据账户查询用户信息
        User user = userFeign.getByName(name);
        if(user!=null){
            //1.查询该用户具有的权限码
            List<Permission> permissionList = permissionFeign.getByUserId(user.getId());

            List<SimpleGrantedAuthority> collect = permissionList.stream().filter(item -> item.getPermissionValue() != null).
                    map(item -> new SimpleGrantedAuthority(item.getPermissionValue())).collect(Collectors.toList());
            return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),collect);
        }
        return null;
    }
}

//1. 多个feign用来同一个微服务spring.main.allow-bean-definition-overriding=true
//2. 自动加载数据源配置类---配置数据源信息@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)